/**
 * 用户相关
 */
import { login, logout, getInfo } from '@/api/user'
//重置路由方法
import { resetRouter } from '@/router'
//操作token
import { getToken, setToken, removeToken } from '@/utils/auth'
import { reject } from 'core-js/fn/promise'

//返回一个初始的state
const getDefaultState = () => {
  return {
    token: getToken(),
    username: '',
    nickname: '',
	avatar:'',
	menus:[]
  }
}

const state = getDefaultState()

const mutations = {
	//重置state
	RESET_STATE: (state) => {
	    Object.assign(state, getDefaultState())
	},
	SET_TOKEN: (state, token) => {
		state.token = token
	},
	SET_USERNAME: (state, username) => {
		state.username = username
	},
	SET_NICKNAME: (state, nickname) => {
		state.nickname = nickname
	},
	SET_AVATAR: (state, avatar) => {
		state.avatar = avatar
	},
	SET_MENUS: (state, menus) => {
		state.menus = menus
	}
}

const actions = {
	//用户登录
	login({ commit }, userInfo){
		//解构用户登录信息
		const { username, password } = userInfo
		return new Promise((resolve, reject) => {
			//登录请求
			login({ username: username.trim(), password: password }).then(response => {
				const { data } = response
				//存储token
				commit('SET_TOKEN', data.token)
				setToken(data.token)
				//不再返回数据
				resolve()
			})
		}).catch(error => {
			reject(error)
		})
	},
	
	//获取用户信息
	getInfo({ commit, state }){
		return new Promise((resolve, reject) => {
			getInfo().then(response => {
				//解构
				const { data } = response
				
				if(!data){
					return reject('登录已超时，请重新登录')
				}
				const { username, nickname, avatar, menus } = data.userInfo
				commit('SET_USERNAME', username)
				commit('SET_NICKNAME', nickname)
				commit('SET_AVATAR', avatar)
				commit('SET_MENUS', menus)
				resolve(data.userInfo)
			})
		}).catch(error => {
			reject(error)
		})
	},
	
	//用户退出
	logout({ commit, state }){
		return new Promise((resolve, reject) => {
			//发起退出登录请求
			logout().then(response => {
				//移除vuex中的token和用户菜单列表
				commit('SET_TOKEN', '')
				commit('SET_MENUS', [])
				//移除缓存中的token
				removeToken()
				//重置静态路由表
				resetRouter()
				//刷新页面
				location.reload()
				resolve()
			})
		}).catch(error => {
			reject(error)
		})
	},
	
	//移除token
	resetToken({ commit }){
		return new Promise((resolve, reject) => {
			//移除vuex中的token和用户菜单列表
			commit('SET_TOKEN', '')
			commit('SET_MENUS', [])
			//移除缓存中的token
			removeToken()
			//重置静态路由表
			resetRouter()
			resolve()
		}).catch(error => {
			reject(error)
		})
	}
}

//导出模块
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
